import { PendingRequest, MessageHandler, RequestProcessor } from './WsClient';

/**
 * WSDispatcher: 网络消息分发与请求管理器
 * - 管理挂起的请求 (PendingRequest)
 * - 注册/派发通知型消息
 * - 注册/处理服务端请求 (双向请求响应)
 */
export class WSDispatcher {
    private pendingRequests: Map<string, PendingRequest> = new Map();
    private messageHandlers: Map<string, MessageHandler> = new Map();
    private requestProcessors: Map<string, RequestProcessor> = new Map();

    /**
     * 注册挂起请求
     */
    public registerPendingRequest(id: string, pendingRequest: PendingRequest): void {
        this.pendingRequests.set(id, pendingRequest);
    }

    /**
     * 注销挂起请求
     */
    public unregisterPendingRequest(id: string): void {
        this.pendingRequests.delete(id);
    }

    /**
     * 检查是否存在挂起请求
     */
    public hasPendingRequest(id: string): boolean {
        return this.pendingRequests.has(id);
    }

    /**
     * 获取指定的挂起请求
     */
    public getPendingRequest(id: string): PendingRequest | undefined {
        return this.pendingRequests.get(id);
    }

    /**
     * 获取所有挂起请求的 ID 列表
     */
    public getAllPendingRequestIds(): string[] {
        return Array.from(this.pendingRequests.keys());
    }

    /**
     * 注册通知型消息处理器
     */
    public registerMessage(type: string, handler: MessageHandler): void {
        this.messageHandlers.set(type, handler);
    }

    /**
     * 注销通知型消息处理器
     */
    public unregisterMessage(type: string): void {
        this.messageHandlers.delete(type);
    }

    /**
     * 派发通知型消息
     */
    public dispatchMessage(type: string, data: any): boolean {
        const handler = this.messageHandlers.get(type);
        if (handler) {
            handler(data);
            return true;
        }
        return false;
    }

    /**
     * 注册服务端请求处理器，客户端收到请求时调用
     */
    public registerProcessor(type: string, processor: RequestProcessor): void {
        this.requestProcessors.set(type, processor);
    }

    /**
     * 注销服务端请求处理器
     */
    public unregisterProcessor(type: string): void {
        this.requestProcessors.delete(type);
    }

    /**
     * 判断是否存在请求处理器
     */
    public hasProcessor(type: string): boolean {
        return this.requestProcessors.has(type);
    }

    /**
     * 处理服务端发起的请求，并返回结果（支持 Promise）
     */
    public async processRequest(type: string, data: any): Promise<any> {
        const processor = this.requestProcessors.get(type);
        if (!processor) throw new Error(`No processor for type: ${type}`);
        return processor(data);
    }

    /**
     * 判断是否存在通知型消息处理器
     */
    public hasHandler(type: string): boolean {
        return this.messageHandlers.has(type);
    }
}
